package com.liusuai.yixian.login;

import com.alibaba.fastjson.JSONObject;
import com.liusuai.yixian.domain.ResultBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


@RestController
public class LoginControler {

    @Autowired
    private RegestService regestService;

    @Autowired
    private LoginService loginService;


    @ResponseBody
    @RequestMapping(value = "/login"
            , method = RequestMethod.POST
            , produces = "application/json;charset=UTF-8")
    public ResultBean login(@RequestBody JSONObject json, HttpServletRequest request) {

        UserBean loginBean = loginService.login(json);
        ResultBean resultBean = new ResultBean();
        if (loginBean != null) {

            HttpSession session = request.getSession(true);

            boolean aNew = session.isNew();
            if (!aNew) {
                session.invalidate();
                System.out.println("------老用户，更新session------old sessionId:" + session.getId());
                session = request.getSession(true);
                System.out.println("new sessionId:" + session.getId());
            } else {
                System.out.println("------新用户，新session------sessionId:" + session.getId());
            }
            session.setMaxInactiveInterval(30 * 60);
            session.setAttribute("userId", loginBean.getId());
            loginService.updateLoginId(loginBean, session.getId());

            resultBean.setCode(100);
            resultBean.setMsg("登录成功");
            resultBean.setSuccess(true);
            resultBean.setData(loginBean);
            return resultBean;

        } else {
            resultBean.setCode(101);
            resultBean.setMsg("登录失败");
            resultBean.setSuccess(false);
        }


        return resultBean;
    }

    @ResponseBody
    @RequestMapping(value = "/regest"
            , method = RequestMethod.POST
            , produces = "application/json;charset=UTF-8")
    public String regest(@RequestBody JSONObject jsonParam) {
        return regestService.regest(jsonParam);
    }

    @ResponseBody
    @GetMapping(value = "/getMessage")
    public String getResponse(@RequestParam String message) {
        return "get test" + message;
    }
}

